<?php
class Log {
	// 日志记录方式
    const SYSTEM 	= 0;
    const MAIL		= 1;
    const FILE		= 3;
    
    // 日志级别 从上到下，由低到高
    const EMERG = 'EMERG';  // 严重错误
    const CRIT = 'CRIT';  // 临界值错误
    const ERR = 'ERR';  // 一般错误
    const WARN = 'WARN';  // 警告性错误
    const NOTICE = 'NOTIC';  // 通知
    const INFO = 'INFO';  // 信息
    const DEBUG = 'DEBUG';  // 调试
    const SQL = 'SQL';  // SQL
    
    static $DateFormat =  'c ';
    static $FilenameFormat =  'ymd';
    
    public static function write( $log, $level = self::INFO, $type = self::FILE )
    {
    	$now = date( self::$DateFormat );
        $outputfile = LOG_PATH.date( self::$FileFormat ).'.log';
        if( self::FILE == $type ) {
            if( is_file( $outputfile ) && floor( config( 'LOG_FILE_SIZE' ) ) <= filesize( $outputfile ) ) {
                  rename( $outputfile, dirname( $outputfile ) . '/' . time() . '-' . basename( $outputfile ) );
            }
        }
        
        error_log( $now.' '.$log.PHP_EOL, $type, $outputfile );
	    if ( config( 'DISPLAY_DEBUG' ) === true ) {
	    	self::html( $log );
	    }
    }
    
    private static function html( $log )
    {
    	echo $log.'<br>';
    }
    
    static function record( $message, $level = self::INFO, $record=false ) 
    {
        if($record || strpos( C( 'LOG_LEVEL' ),$level ) ) {
            $now = date( self::$format );
            self::$log[] =   "{$now} " . $_SERVER['REQUEST_URI'] . " | {$level}: {$message}" .PHP_EOL;
        }
    }
    
    static function save( $type='', $destination='', $extra='' ) {
        $type = $type ? $type : C( 'LOG_TYPE' );
        if( self::FILE == $type ) { // 文件方式记录日志信息
            if( empty( $destination ) )
                $destination = LOG_PATH.date('y_m_d').'.log';
            //检测日志文件大小，超过配置大小则备份日志文件重新生成
            if(is_file($destination) && floor(C('LOG_FILE_SIZE')) <= filesize($destination) )
                  rename($destination,dirname($destination).'/'.time().'-'.basename($destination));
        }else{
            $destination   =   $destination?$destination:C('LOG_DEST');
            $extra   =  $extra?$extra:C('LOG_EXTRA');
        }
        error_log(implode('',self::$log), $type,$destination ,$extra);
        // 保存后清空日志缓存
        self::$log = array();
        //clearstatcache();
    }
}
?>